package com.example.transaction_springboot.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.transaction_springboot.entity.Admin;
import com.example.transaction_springboot.exception.ServiceException;
import com.example.transaction_springboot.mapper.AdminMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private AdminMapper adminMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            //如果请求头中没有token，则从请求参数中获取token
            token = request.getParameter("token");
        }
        //如果不是映射到方法直接通过
        if (handler instanceof HandlerMethod){
            AuthAccess authAccess = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
            if (authAccess != null) return true;
        }

        //执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("401", "请登录");
        }

        //获取token中的userId
        String admidId;
        try {
            admidId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new ServiceException("401", "请登录");
        }

        //根据userId查询用户信息
        Admin admin = adminMapper.selectById(Integer.valueOf(admidId));
        if (admin == null) {
            throw new ServiceException("401", "请登录");
        }

        //通过用户密码加密之后生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
        try {
            jwtVerifier.verify(token);  //验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException("401", "请登录");
        }

        return true;
    }
}
